import WebSocket from "ws";
import InputStream from "./stream";
import {ResponseOperate} from "./opearte";
import convert from "./packet/resp/resp.convert";
import eventBus from "./EventBus";

export class  ChannelServer {
    constructor(private ip: string, private port: number) {

    }
    ws:WebSocket
    async   init(){
        const ws = new WebSocket(`ws://${this.ip}:${this.port}/ws`);
        this.ws=ws;
        ws.binaryType = 'arraybuffer';



        ws.on('message', (data) => {
            console.log(data);

            const array=new Int8Array(data as ArrayBuffer);
            const stream=new InputStream(array);
            const type= stream.readInt() as ResponseOperate;
            let message = convert(type,stream);
            // console.info(message)
            eventBus.emit(type,message)





        });


        ws.on('close', () => {
            console.log('Disconnected from WebSocket server');
        });
        return new Promise<void>((resolve, reject)=>{
            ws.on('open', () => {
                console.info(`连接${this.ip}:${this.port}成功`)
                resolve()


            });
        })



    }
    close(){
        this.ws.close();
    }
   async  switchChannel(ip:string,port:number){
        this.ip=ip;
        this.port=port;
         this.close();
         await  this.init();
    }
    send(data:Int8Array){
        this.ws.send(data);
    }

}